package com.br4mmie.asciistory.ui;
import java.util.*;

import com.br4mmie.asciistory.ASCIIStoryActivity;
import com.br4mmie.asciistory.CharImage;
import com.br4mmie.asciistory.Keybindings;
import com.br4mmie.asciistory.mission.Mission;


public class Journal extends Window
{
	private ArrayList<Mission> missions;
	private int selection; 
	private int scroll;
	
	public Journal(ArrayList<Mission> missions)
	{
		super(2, 2, 46, 11);
		
		this.missions = missions;
		this.selection = 0;
		this.scroll = 0;
	}
	
	public void handleEvents()
	{
		try 
		{
			if (Keybindings.UP.pressed() && selection > 0)
			{
				selection --;
				if (selection - scroll < 2 && scroll > 0) scroll--;
				Thread.sleep(ASCIIStoryActivity.keyDelay);
			}
			if (Keybindings.DOWN.pressed() && selection < missions.size())
			{
				selection ++;
				if (selection - scroll > 5 && scroll < missions.size()) scroll++;
				Thread.sleep(ASCIIStoryActivity.keyDelay);
			}
			if (Keybindings.INTERACT.pressed() && 
				selection >= 0 &&
				selection <  missions.size())
			{
				Mission m = missions.get(selection);
				m.showInfoWindow();
			}
		}
		catch (Exception ex) {}
		super.handleEvents();
	}
	public void draw(CharImage target)
	{
		image.fill(' ');
		
		CharImage text = new CharImage(21, 1);
		
		text.setImage("Journal              ");
		text.draw(image, 1, 1);
		image.line('|', image.getWidth()-5, 3, image.getWidth()-5, image.getHeight()-1);
		image.line('-', 0, 2, image.getWidth(), 2);
		
		int y = 3;
		int i = 0;
		for (Mission m: missions)
		{
			if (i < scroll) {i++;continue;}
			
			char[] chars = m.getName().toCharArray();
			
			int x = 2;
			for (char c: chars)
			{
				image.putChar(c, x++, y);
			}
			
			if (selection == i)
			{
				image.putChar('(', 1, y);
				image.putChar(')', x, y);
			}
			
			if (m.isFinished())
			{
				image.putChar(' ', image.getWidth()-4, y);
				image.putChar('V', image.getWidth()-3, y);
				image.putChar(' ', image.getWidth()-2, y);
			}
			else
			{
				image.putChar('.', image.getWidth()-4, y);
				image.putChar('.', image.getWidth()-3, y);
				image.putChar('.', image.getWidth()-2, y);
			}
			
			y++;
			i++;
			if (i > 6+scroll) break;
		}
		
		super.draw(target);
	}
}
